package servlets;

import java.io.IOException;
import javaPersistence.Client;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import beans.FormData;

/**
 * Servlet implementation class LoadDataClient
 */
@WebServlet("/LoadClient")
public class LoadDataClient extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoadDataClient() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int update = 0;
		String codClient = "";
		String nameClient = "";
		String addrClient = "";
		String phoClient = "";
		String emailClient = "";
		try {
			HttpSession sess = request.getSession();
			FormData fdata = new FormData();
			Client client = new Client();
			update = Integer.parseInt(request.getParameter("update"));
			if(update == 1)
				codClient = request.getParameter("codClientAux");
			else
				codClient = request.getParameter("codClient");
			nameClient = request.getParameter("nameClient");
			addrClient = request.getParameter("addrClient");
			phoClient = request.getParameter("phoClient");
			emailClient = request.getParameter("emailClient");
			if(codClient != null && nameClient != null && addrClient != null && phoClient != null && emailClient != null){
				if(update == 0){
					if(!client.insertClient(codClient, nameClient, addrClient, phoClient, emailClient)){
						fdata.setError("Error: Los datos insertados ya existen o estan mal diligenciados.");
					}else{
						fdata.setMsgOK("OK: Los datos fueron almacenados correctamente.");
						fdata.setClients(client.loadAllClient());
					}
				}else{
					if(!client.updateClient(codClient, nameClient, addrClient, phoClient, emailClient)){
						fdata.setError("Error: Los datos insertados ya existen o estan mal diligenciados.");
					}else{
						fdata.setMsgOK("OK: Los datos fueron actualizados correctamente.");
						fdata.setClients(client.loadAllClient());
					}
				}
			}else{
				fdata.setError("TODOS: Los datos son necesarios");
			}
			sess.setAttribute("FormData", fdata);
			response.sendRedirect(request.getContextPath() + "/jsps/negocio/clientes.jsp");
		} catch (Exception e) {
		}
		
	}

}
